
package com.island.practice.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.island.practice.entity.Role;


/**
 * The sevelet class to insert Person into database
 */
public class CreatePersonServlet extends AbstractServlet {
	
	private static final String SQL_INSERT_PERSON = 
		"INSERT INTO PERSON(PERSON_ID, LAST_NAME, FIRST_NAME) VALUES(?, ?, ?)";
	private static final String SQL_QUERY_ROLES =
			"SELECT r.* FROM ROLE r";
	/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws IOException 
	 * @throws SQLException 
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, SQLException {
    	//Get the data from user's form
    	String personId		= request.getParameter("personId");
        String firstName 	= request.getParameter("firstName");
        String lastName 	= request.getParameter("lastName");
        String[] roleIds 	= request.getParameterValues("roleId");
    	
        Connection connection = null;
        PreparedStatement statement = null;

        try {
        	connection = this.getConnection();
        	//HEAD: transaction boundary
        	connection.setAutoCommit(false);
					
	        //1. insert person
	    	insertPerson(personId, firstName, lastName, connection);
	    	
	    	//4. insert person_roles relationship
	    	insertPersonRolesRelationship(personId, roleIds, connection);
    	
        } catch (SQLException e) {
			e.printStackTrace();
			connection.rollback();
			throw new RuntimeException("insert person failed", e);
		} catch(NullPointerException e){
			connection.rollback();
			throw new RuntimeException("Have some empty field.", e);
		}finally {
			closeStatement(statement);
			//TAIL: transaction boundary
			closeConnection(connection);
		}
        
    	request.getRequestDispatcher("/person/ListPerson").forward(request, response);
    	
    }

	private void insertPerson(String personId, String firstName, String lastName, Connection connection)
			throws SQLException {
		PreparedStatement statement = null;
		
		try {
			statement = connection.prepareStatement(SQL_INSERT_PERSON);
			statement.setString(1, personId);
			statement.setString(2, lastName);
			statement.setString(3, firstName);
			statement.execute();
		} finally {
			closeStatement(statement);
		}
	}
	
	// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        /*
		 * 得到所有ROLE
		 * */
    	ArrayList<Role> allRole = null;
		Role role = null;
		ResultSet resultSet = null;
        Connection connection = null;
        PreparedStatement statement = null;
		try {
			allRole = new ArrayList<Role>();
			connection = this.getConnection();
			statement = connection.prepareStatement(SQL_QUERY_ROLES);
			resultSet = statement.executeQuery();
			while(resultSet.next()){
				role = new Role();
				role.setRoleId(resultSet.getString("ROLE_ID"));
				role.setRoleName(resultSet.getString("ROLE_NAME"));
				
				allRole.add(role);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			closeStatement(statement);
			closeConnection(connection);
		}
		request.setAttribute("allRole", allRole);
		request.setAttribute("allRoleId", getChangeAllRoleToString(allRole));
		
		request.getRequestDispatcher("/person/CreatePerson.jsp").forward(request, response);
        //processRequest(request, response);
    }
    
	/*------未了自動完成所需之DATA 將物件中的屬性轉字串
	 *  格式：  "A,B,C,...,Z" ----------------------------*/
	private String getChangeAllRoleToString(ArrayList<Role> allRole){
		StringBuffer allRolesString = new StringBuffer();
		for (int i = 0; i < allRole.size(); i++) {
			Role role = allRole.get(i);
			if(i == 0){
				allRolesString.append("'" + role.getRoleName() + "'");
			} else{
				allRolesString.append(", '" + role.getRoleName() + "'");
			}	
		}
		return allRolesString.toString();
	}
	/*-------------------------------------*/
    
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException{
    	
        try {
			processRequest(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println(e.toString());
		}
    }
}
